import requests
import os
import json
import time
from pathlib import Path
from datetime import datetime

DEVICE_ID = "DEV-123456"  # 唯一设备标识
UPLOAD_API = "http://47.93.172.78:8081/upload"
DEVICE_ADD_API = "http://47.93.172.78:8081/devices"
SICK_ADD_API = "http://47.93.172.78:8081/"
LAST_UPLOAD_FILE = "last_upload.txt"  # 时间戳存储文件
TOKEN_FILE = "auth.token"
MONITOR_DIRS = [  # 要监控的文件夹列表
    "./sick/bacterial_blight/",
    "./sick/brown_spot/",
    "./sick/rice_blast/",
    "./pest/rice_leafhopper",
    "./pest/rice_leaf_roller",
    "./pest/rice_water_weevil"
]

# 初始化全局变量
last_upload_time = 0
current_token = ''
def load_token():
    global current_token
    token_file = Path(TOKEN_FILE)
    if token_file.exists():
        try:
            with open(token_file, "r") as f:
                # 修复2：去除首尾空白字符（包括换行符）
                current_token = f.read().strip()  
                # 调试：打印加载的 Token（实际使用时可以注释）
                #print(f"[DEBUG] 从文件加载的 Token: {current_token}")
        except Exception as e:
            print(f"加载 Token 文件失败: {str(e)}")
            current_token = ''
    else:
        print(f"错误：Token 文件 {TOKEN_FILE} 不存在")
        current_token = ''

def save_token(token):
    """保存token到文件"""
    token_file = Path(TOKEN_FILE)
    if token_file.exists():
        try:
            with open(token_file, "w") as f:
                f.write(token)
            print("🔑 Token保存成功")
        except Exception as e:
            print(f"❌ 保存Token失败: {str(e)}")
    else:
        Path(f'{TOKEN_FILE}').touch()
        print(f"创建token文件: {TOKEN_FILE}")


def handle_upload_command():
    # 加载上次上传时间
    global last_upload_time
    load_token()  # 新增：加载令牌

    # 修复：安全加载时间戳
    last_upload_file = Path(LAST_UPLOAD_FILE)
    if last_upload_file.exists():
        try:
            with open(LAST_UPLOAD_FILE, "r") as f:
                content = f.read().strip()
                # 检查内容是否为空或无效
                if content:
                    last_upload_time = float(content)
                else:
                    last_upload_time = 0  # 空内容时初始化为0
        except ValueError:
            last_upload_time = 0  # 内容格式错误时也初始化为0
    else:
        last_upload_time = 0  # 文件不存在时初始化为0
   
   # 获取最新图片
    new_files = []
    for dir_path in MONITOR_DIRS:
        target_dir = Path(dir_path)
        if not target_dir.exists():
            print(f"警告: 目录 {dir_path} 不存在，跳过扫描")
            continue
        for file in target_dir.glob("*.jpg"):
            mtime = file.stat().st_mtime
            print(file.name,mtime)
            if mtime > last_upload_time:
                new_files.append(file)

    # 上传文件
    if new_files:
        print(f"发现 {len(new_files)} 个新文件需要上传")
        for file in sorted(new_files, key=lambda x: x.stat().st_mtime):
            upload_file(file)
            update_last_upload(file.stat().st_mtime)
    else:
        print("没有新文件需要上传")

def upload_file(file_path):
    try:
        # 获取文件夹名称
        folder_name = file_path.parent.name
        folder_name_parent = file_path.parent.parent.name
        with open(file_path, "rb") as f:
            files = {"file": (file_path.name, f)}
            headers = {"Authorization": f"{current_token}"}
            data = {
                "category": folder_name
            }
            r = requests.post(UPLOAD_API, files=files, data=data
                    , headers=headers)
            datas = r.json()
            if r.status_code == 200:
                print(f"成功上传:{folder_name}下的{file_path.name}")
                print(f"URL: {datas['data']}")
                # 上传成功的同时直接更新数据库
                data = {
                    "category":folder_name,
                    "detectImg":datas['data'],
                        }
                requests.post(SICK_ADD_API+folder_name_parent, json=data, headers=headers)
                return True
            else:
                print(f"上传失败: {r.text}")
                print(r.status_code)
                return False
    except Exception as e:
        if 'r' in locals():  # 检查r是否存在
            print(f"请求失败，状态码: {r.status_code}")
        print(f"上传异常: {str(e)}")
        return False

def update_last_upload(timestamp):
    global last_upload_time
    if timestamp > last_upload_time:
        last_upload_time = timestamp
        with open(LAST_UPLOAD_FILE, "w") as f:
            f.write(str(last_upload_time))

def add_device(state,device_id):
    load_token()  # 加载令牌
    try:
        headers = {"Authorization": f"{current_token}"}
        data = {
            "deviceId": device_id,
            "state": state
        }
        r = requests.post(DEVICE_ADD_API, json=data, headers=headers)
        if r.status_code == 200:
                print(f"新增设备:{device_id}")
                return True
        else:
            print(f"新增失败: {r.text}")
            print(r.status_code)
            return False
    except Exception as e:
        if 'r' in locals():  # 检查r是否存在
            print(f"请求失败，状态码: {r.status_code}")
        print(f"上传异常: {str(e)}")
        return False


if __name__ == "__main__":
	state="active"
	add_device(state)

